const inquirer = require('inquirer')
const readline = require('readline')
const packageJson = require('../../package')

const questions = [
    {
        type: 'list',
        name: 'env',
        message: '请选择环境：',
        choices: ['dev', 'test', 'prod']
    },
    {
        type: 'list',
        name: 'arch',
        message: '请选择构建包 64/32 位：',
        choices: ['x64', 'ia32']
    },
    {
        type: 'list',
        name: 'target',
        message: '请选择构建方式：',
        choices: ['normal', 'dir', 'prepackaged']
    },
    {
        type: 'confirm',
        name: 'codeSign',
        message: '需要代码签名吗？',
        default: false
    },
    {
        type: 'confirm',
        name: 'rebuildJS',
        message: '需要重新打包吗？',
        default: true,
        when(answer) {
            return answer.target !== 'prepackaged'
        }
    },
    {
        type: 'input',
        name: 'version',
        message: '请输入版本号：',
        default: packageJson.version,
        validate(answer) {
            try {
                const nums = answer.split('.')
                if (nums.length !== 3) {
                    throw new Error('invalid')
                }

                for (const n of nums) {
                    if (!/\d/.test(n)) {
                        throw new Error('invalid')
                    }
                }

                return true
            } catch (error) {
                return '无效的版本号！'
            }
        }
    }
];

function clearConsole() {
    if (process.stdout.isTTY) {
        const blank = '\n'.repeat(process.stdout.rows)
        console.log(blank)
        readline.cursorTo(process.stdout, 0, 0)
        readline.clearScreenDown(process.stdout)
    }
}

module.exports = async () => {
    clearConsole();
    const answer = await inquirer.prompt(questions);
    return answer;
}
